import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
// const service = axios.create({
//   baseURL: process.env.BASE_API, // api的base_url
//   timeout: 120000 // 请求超时时间
// })
const service = axios.create({
    // 郭星本地
    // baseURL: 'http://10.183.44.64:9000',
    // 郑鑫欣本地
    // baseURL: 'http://10.183.44.64:9000',
    // 刘刚本地
    // baseURL: 'http://192.168.137.19:9000',
    // 厍桥平本地
    // baseURL: 'http://10.183.44.64:9000',
    // 叶正勇本地
    // baseURL: 'http://10.183.44.84:9000',
    // 测试环境地址
    baseURL: 'http://10.12.18.89:9000',
    // 业务测试环境
    // baseURL: 'http://10.12.18.95:9000',
    //timeout: 120000, // 请求超时时间
    timeout: 3000000, // 请求超时时间
    withCredentials: true,
});

//获取当前时间
Date.prototype.Format = function(fmt) {
  var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "H+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

// request拦截器
service.interceptors.request.use(config => {
    // 不走统一封装白名单
    let whiteUrl = [
          'lclaim-report/report/import/importCaseInfo',
          'lclaim-report/report/print/printSettleBill'
        ];
    let flag  = true;
    whiteUrl.findIndex(item => {
      if(item === config.url){
        flag = false;
      }
    })
    if(flag){
        let obj = config.data.body;
        if (obj == '' || obj == undefined || obj == null){
            obj = config.data;
        }
        let data = {
            head: {
                systemSource: 'web',
//                serviceName: '登录',
//                serviceType: 'cmo',
                requestTime: new Date().Format("yyyy-MM-dd HH:mm:ss"),
                token: getToken(),
                taskType:obj.taskType || ''//增加入参数 任务类型
            },
            body: obj || {}
        }
        config.data = data;
    }

  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
    const res = response //.data
    if (res.status !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })

      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject('error')
    } else {
      // let obj = {
      // }
      let whiteUrl = [
            'lclaim-report/report/export/exportBatchClaimTemplate',
            'lclaim-report/report/export/exporttBatchClaim',
            'lclaim-report/report/print/printSettleBill',
            'lclaim-report/report/export/exportCaseReportInfo'
          ];
      let responseUrl = response.config.url
      let index = response.config.baseURL.length;
      responseUrl = responseUrl.substring(index+1,responseUrl.length);
      let flag  = true;
      whiteUrl.findIndex(item => {
        if(item === responseUrl){
          flag = false;
        }
      })
      let obj = response.data;
      if(response.data.code === undefined && flag){
        obj = {}
        if (response.data.body && response.data.head.resultCode =='0000') {
            obj = {
                data: response.data.body,
            }
            obj.data.resultCode = '0000';
            obj.data.resultMsg = response.data.head.resultMsg;
        } else {
            obj = {}
            obj.data = response.data.head
        }
      }
      return obj;
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
